//
//  common.m
//  NVAReader
//
//  Created by DuyLK on 6/4/14.
//  Copyright (c) 2014 com.nva.nvareader. All rights reserved.
//

#import "common.h"


fz_context *ctx;
dispatch_queue_t queue;
float screenScale = 1;

CGSize fitPageToScreen(CGSize page, CGSize screen)
{
	float hscale = screen.width / page.width;
	float vscale = screen.height / page.height;
	float scale = fz_min(hscale, vscale);
	hscale = floorf(page.width * scale) / page.width;
	vscale = floorf(page.height * scale) / page.height;
	return CGSizeMake(hscale, vscale);
}

static int hit_count = 0;
static fz_rect hit_bbox[500];

int search_page(fz_document *doc, int number, char *needle, fz_cookie *cookie)
{
	fz_page *page = fz_load_page(doc, number);
    
	fz_text_sheet *sheet = fz_new_text_sheet(ctx);
	fz_text_page *text = fz_new_text_page(ctx);
	fz_device *dev = fz_new_text_device(ctx, sheet, text);
	fz_run_page(doc, page, dev, &fz_identity, cookie);
	fz_free_device(dev);
    
	hit_count = fz_search_text_page(ctx, text, needle, hit_bbox, nelem(hit_bbox));
    
	fz_free_text_page(ctx, text);
	fz_free_text_sheet(ctx, sheet);
	fz_free_page(doc, page);
    
	return hit_count;
}

fz_rect search_result_bbox(fz_document *doc, int i)
{
	return hit_bbox[i];
}

static void releasePixmap(void *info, const void *data, size_t size)
{
	if (queue)
		dispatch_async(queue, ^{
			fz_drop_pixmap(ctx, info);
		});
	else
	{
		fz_drop_pixmap(ctx, info);
	}
}

CGDataProviderRef wrapPixmap(fz_pixmap *pix)
{
	unsigned char *samples = fz_pixmap_samples(ctx, pix);
	int w = fz_pixmap_width(ctx, pix);
	int h = fz_pixmap_height(ctx, pix);
	return CGDataProviderCreateWithData(pix, samples, w * 4 * h, releasePixmap);
}

CGImageRef newCGImageWithPixmap(fz_pixmap *pix, CGDataProviderRef cgdata)
{
	int w = fz_pixmap_width(ctx, pix);
	int h = fz_pixmap_height(ctx, pix);
	CGColorSpaceRef cgcolor = CGColorSpaceCreateDeviceRGB();
	CGImageRef cgimage = CGImageCreate(w, h, 8, 32, 4 * w, cgcolor, kCGBitmapByteOrderDefault, cgdata, NULL, NO, kCGRenderingIntentDefault);
	CGColorSpaceRelease(cgcolor);
	return cgimage;
}

int colorCode (NSColor *color)
{
    CGFloat red, green, blue, alphat;
    [color getRed:&red green:&green blue:&blue alpha:&alphat];
    int redInt = (int)(red * 255 + 0.5);
    int greenInt = (int)(green * 255 + 0.5);
    int blueInt = (int)(blue * 255 + 0.5);
    int alphaInt = (int)(alphat * 255 + 0.5);
    return (alphaInt <<24) | (redInt << 16) | (greenInt << 8) | blueInt;
}

NSColor* colorDecode(int color){
    float alphaInt = (float)(color>>24 & 0x000000FF)/255.0;
    float redInt = (color>>16 & 0x000000FF)/255.0;
    float greenInt = (color>>8 & 0x000000FF)/255.0;
    float blueInt = (color & 0x000000FF)/255.0;
    NSColor *colortemp = [NSColor colorWithCalibratedRed:redInt green:greenInt blue:blueInt alpha:alphaInt];
    return colortemp;
}
